package com.sntk.organauthomanager.domain.model;

import com.sntk.organauthomanager.infrastructure.exception.UserRoleOrganMatchException;
import lombok.Getter;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @作者：wgchao
 * @时间：21:03 2020/7/18 0018
 * @用途：用户角色对应关系
 **/
@Getter
public class UserRole extends AggregateRoot {
    //唯一
    private String uname;
    //拥有角色
    private Set<RoleIdentify> roleIdentifies;

    public UserRole(Long id, String uname, Set<RoleIdentify> roleIdentifies) {
        setId(id);
        this.uname = uname;
        this.roleIdentifies = roleIdentifies;
    }

    public UserRole(Organization organization, User user, List<Role> roles){
        organization.normalException();
        user.normalException();
        this.uname = user.getUname();
        if(roles==null || roles.isEmpty()){
            this.roleIdentifies = null;
        }else{
            this.roleIdentifies = new HashSet<>();
            for(Role role : roles){
                role.normalException();
                if(!organization.getInstitutionNumber().equals(user.getInstitutionNumber()) ||
                        !organization.getInstitutionNumber().equals(role.getRoleIdentify().getInstitutionNumber()) ){
                    throw new UserRoleOrganMatchException();
                }
                this.roleIdentifies.add(role.getRoleIdentify());
            }
        }
    }
}
